#include "Logger.h"
#include <ctime>
#include <filesystem>
#include <cstring>

namespace fs = std::filesystem;  // 使用命名空间别名简化代码


// 初始化静态成员变量
Logger* Logger::instance = nullptr;

Logger::Logger() {
    fs::path path0 =  fs::absolute("app.log");
    std::cout << "- Log file path : " << path0.string() << std::endl;
        std::cerr << "- logger " <<this << std::endl;
    logFile.open(path0, std::ios::app);
    if (!logFile.is_open()) {
        std::cerr << "can not open log file" << std::endl;
    }
}

Logger::~Logger() {
    if (logFile.is_open()) {
        logFile.close();
    }
}

Logger* Logger::getInstance() {
    if (instance == nullptr) {
        instance = new Logger();
    }
    return instance;
}

void Logger::destroyInstance() {
    auto a = getInstance();
    if (a != nullptr) {
        std::cerr << "- destroyInstance " <<a << std::endl;
        delete a;
        a = nullptr;
    }
}

void Logger::log(const std::string& message) {
    if (logFile.is_open()) {
        time_t now = time(0);
        char* dt = ctime(&now);
        dt[strlen(dt) - 1] = '\0'; // 移除换行符
        logFile << "[" << dt << "] INFO: " << message << std::endl;
    }
}

void Logger::logError(const std::string& message) {
    if (logFile.is_open()) {
        time_t now = time(0);
        char* dt = ctime(&now);
        dt[strlen(dt) - 1] = '\0';
        logFile << "[" << dt << "] ERROR: " << message << std::endl;
    }
}

void Logger::logWarning(const std::string& message) {
    if (logFile.is_open()) {
        time_t now = time(0);
        char* dt = ctime(&now);
        dt[strlen(dt) - 1] = '\0';
        logFile << "[" << dt << "] WARNING: " << message << std::endl;
    }
} 